package com.cuanbo.dualscreenteachzhu.utils;

import android.util.Base64;
import android.util.Log;

import java.security.MessageDigest;

/**
 *加密工具
 */
public class EncryptionUtil {
    //密钥
    public final static String key = "Ht12345.";

    /**
     * 加密
     * @param content 要加密的字符串
     */
    public static String encrypt(String content) {
        try {
            String contentBase64 = new String(Base64.encode(content.getBytes("utf-8"), Base64.DEFAULT));
            Log.i("luohao", "encrypt contentBase64=" + contentBase64);
            String keyBase64 = new String(Base64.encode(key.getBytes("utf-8"), Base64.DEFAULT));
            Log.i("luohao", "encrypt keyBase64=" + keyBase64);
            String bbContent = (contentBase64 + keyBase64).replace("=", "").replace("\n", "");
            Log.i("luohao", "encrypt bbContent=" + bbContent);
            return new String(Base64.encode(bbContent.getBytes("utf-8"), Base64.DEFAULT));
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * 解密
     * @param content 要解密的字符串
     */
    public static String decrypt(String content) {
        try {
            String contentBase64 = new String(Base64.decode(content.getBytes("utf-8"), Base64.DEFAULT));
            Log.i("luohao", "decrypt contentBase64=" + contentBase64);
            String keyBase64 = new String(Base64.encode(key.getBytes("utf-8"), Base64.DEFAULT));
            Log.i("luohao", "decrypt keyBase64=" + keyBase64);
            String bbContent = contentBase64.substring(0, contentBase64.length() - keyBase64.length() + 2) + "=\n";
            Log.i("luohao", "decrypt bbContent=" + bbContent);
            return new String(Base64.decode(bbContent.getBytes("utf-8"), Base64.DEFAULT));
        } catch (Exception e) {
        }
        return null;
    }

    /**
     *字符串转MD5
     * @param info 字符串
     */
    public static String toMD5(String info) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(info.getBytes("UTF-8"));
            byte[] encryption = md5.digest();

            StringBuffer strBuf = new StringBuffer();
            for (int i = 0; i < encryption.length; i++) {
                if (Integer.toHexString(0xff & encryption[i]).length() == 1) {
                    strBuf.append("0").append(Integer.toHexString(0xff & encryption[i]));
                } else {
                    strBuf.append(Integer.toHexString(0xff & encryption[i]));
                }
            }
            return strBuf.toString();
        } catch (Exception e) {
            return "";
        }
    }
}
